﻿using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using AlibabaCloud.TeaUtil.Models;
using Tea;

namespace Provenance.Read.Api.Utilities
{
    /// <summary>
    /// 短信客户端工厂 
    /// </summary>
    public class SmsClientFactory
    {
        private readonly IConfiguration _configuration;
        public SmsClientFactory(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient()
        {
            var accessKeyId = _configuration["Aliyun:AccessKeyId"];
            var accessKeySecret = _configuration["Aliyun:AccessKeySecret"];

            var config = new Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessKeySecret,
                Endpoint = "dysmsapi.aliyuncs.com"
            };
            return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumber">手机号</param>
        /// <param name="templateParam">模版参数</param>
        /// <param name="signName">签名</param>
        /// <param name="templateCode">模版编号</param>
        public void SendSms(string phoneNumber,string templateParam,string signName,string templateCode)
        {
            var client = CreateClient();
            var sentSmsRequest = new SendSmsRequest
            {
                SignName = signName,
                TemplateCode = templateCode,
                PhoneNumbers = phoneNumber,
                TemplateParam = templateParam
            };
            var runtime = new RuntimeOptions();
            try
            {
                var response=client.SendSmsWithOptions(sentSmsRequest, runtime);
                Console.WriteLine("SMS send successfully:" + response.Body);
            }
            catch (TeaException error)
            {
                // 记录错误信息
                Console.WriteLine("Error: " + error.Message);
                Console.WriteLine("Recommendation: " + error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
            catch (Exception ex)
            {
                var error = new TeaException(new Dictionary<string, object>
                {
                    { "message", ex.Message }
                });
                // 记录错误信息
                Console.WriteLine("Error: " + error.Message);
                Console.WriteLine("Recommendation: " + error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
        }




    }
}
